Telegram Group & Telegram Channel
🎯 Как быстро настроить кеширование в Spring Boot

Писать кеш руками через HashMap или страдать с вручную настроенными TTL — скучно, долго и ненадёжно. В Spring Boot всё уже готово: включаем, настраиваем, и поехали!

1️⃣ Добавляем зависимость

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>

ИЛИ

implementation 'org.springframework.boot:spring-boot-starter-cache'


2️⃣ Включаем кеширование

Добавляем простую аннотацию над главным классом приложения (или конфиг классом):
@SpringBootApplication
@EnableCaching
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}


3️⃣ Кешируем методы сервисов

Используем аннотацию @Cacheable на тех методах, которые часто выполняются и редко меняются:
@Service
public class UserService {

@Cacheable(value = "users", key = "#id")
public User getUserById(Long id) {
simulateSlowService();
return userRepository.findById(id).orElseThrow();
}

private void simulateSlowService() {
Thread.sleep(3000);
}
}


Теперь при повторном вызове метода с тем же параметром ответ прилетит мгновенно.

4️⃣ Настройка TTL и конфигурация кеша

В Spring Boot по умолчанию используется простой ConcurrentMap (без TTL). Если хочешь TTL и прочие плюшки, подключайте Caffeine:

spring:
cache:
type: caffeine
caffeine:
spec: maximumSize=500,expireAfterAccess=10m


Кеш будет жить максимум 10 минут и не разрастаться до бесконечности.

5️⃣ Очистка кеша

Если нужно принудительно почистить кеш после обновления данных, используем @CacheEvict:
@CacheEvict(value = "users", key = "#id")
public void updateUser(Long id, User updatedUser) {
userRepository.save(updatedUser);
}


💬 Хранили когда-нибудь кеш в мапе?

🐸 Библиотека джависта #буст
Please open Telegram to view this post
VIEW IN TELEGRAM



tg-me.com/javaproglib/6561
Create:
Last Update:

🎯 Как быстро настроить кеширование в Spring Boot

Писать кеш руками через HashMap или страдать с вручную настроенными TTL — скучно, долго и ненадёжно. В Spring Boot всё уже готово: включаем, настраиваем, и поехали!

1️⃣ Добавляем зависимость

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>

ИЛИ

implementation 'org.springframework.boot:spring-boot-starter-cache'


2️⃣ Включаем кеширование

Добавляем простую аннотацию над главным классом приложения (или конфиг классом):
@SpringBootApplication
@EnableCaching
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}


3️⃣ Кешируем методы сервисов

Используем аннотацию @Cacheable на тех методах, которые часто выполняются и редко меняются:
@Service
public class UserService {

@Cacheable(value = "users", key = "#id")
public User getUserById(Long id) {
simulateSlowService();
return userRepository.findById(id).orElseThrow();
}

private void simulateSlowService() {
Thread.sleep(3000);
}
}


Теперь при повторном вызове метода с тем же параметром ответ прилетит мгновенно.

4️⃣ Настройка TTL и конфигурация кеша

В Spring Boot по умолчанию используется простой ConcurrentMap (без TTL). Если хочешь TTL и прочие плюшки, подключайте Caffeine:

spring:
cache:
type: caffeine
caffeine:
spec: maximumSize=500,expireAfterAccess=10m


Кеш будет жить максимум 10 минут и не разрастаться до бесконечности.

5️⃣ Очистка кеша

Если нужно принудительно почистить кеш после обновления данных, используем @CacheEvict:
@CacheEvict(value = "users", key = "#id")
public void updateUser(Long id, User updatedUser) {
userRepository.save(updatedUser);
}


💬 Хранили когда-нибудь кеш в мапе?

🐸 Библиотека джависта #буст

BY Библиотека джависта | Java, Spring, Maven, Hibernate




Share with your friend now:
tg-me.com/javaproglib/6561

View MORE
Open in Telegram


Библиотека джависта | Java Spring Maven Hibernate Telegram | DID YOU KNOW?

Date: |

Telegram Auto-Delete Messages in Any Chat

Some messages aren’t supposed to last forever. There are some Telegram groups and conversations where it’s best if messages are automatically deleted in a day or a week. Here’s how to auto-delete messages in any Telegram chat. You can enable the auto-delete feature on a per-chat basis. It works for both one-on-one conversations and group chats. Previously, you needed to use the Secret Chat feature to automatically delete messages after a set time. At the time of writing, you can choose to automatically delete messages after a day or a week. Telegram starts the timer once they are sent, not after they are read. This won’t affect the messages that were sent before enabling the feature.

Tata Power whose core business is to generate, transmit and distribute electricity has made no money to investors in the last one decade. That is a big blunder considering it is one of the largest power generation companies in the country. One of the reasons is the company's huge debt levels which stood at ₹43,559 crore at the end of March 2021 compared to the company’s market capitalisation of ₹44,447 crore.

Библиотека джависта | Java Spring Maven Hibernate from us


Telegram Библиотека джависта | Java, Spring, Maven, Hibernate
FROM USA